﻿using UnityEngine;
using System.Collections;
using System.IO;
using UnityEngine.UI;
using System.Collections.Generic;

public class LoadImage : MonoBehaviour
{
    //资源路径
    private string filePath="";
    private string saveFilePath = "";
    public Image image;
    public Image image1;
    public GameObject btn_IOLoad;
    public GameObject btn_WWWLoad;
    public GameObject btn_Clear;
    public GameObject btn_Save;

    public Text tips;
    //写入persistentDataPath目录文件
    private List<string> hadWriteFileList = new List<string>();

    //资源列表
    public Dropdown Drd_JpgList;
    private string fileName;
    private string HadCopyTxt = "hadCopyTxt.txt";

    // Use this for initialization
    void Start()
    {
        saveFilePath = Application.persistentDataPath+"/";
        Debug.Log("persistentDataPath:" + saveFilePath);
        FileHelper fileHelp = new FileHelper();
        hadWriteFileList = fileHelp.LoadFile(saveFilePath, HadCopyTxt);
    
        foreach (var item in hadWriteFileList)
        {
            tips.text += item+"\n";
        }

        filePath =
#if UNITY_ANDROID && !UNITY_EDITOR
              "jar:file:///" + Application.dataPath + "!/assets/";
#elif UNITY_IPHONE && !UNITY_EDITOR
               file:// + Application.dataPath +"/Raw/"
#elif UNITY_STANDALONE_WIN || UNITY_EDITOR
              "file://" + Application.dataPath + "/StreamingAssets/";
#else
               string.Empty;  
#endif


        Debug.Log(filePath);
        btn_IOLoad.GetComponent<Button>().onClick.AddListener(OnIOLoadClick);
        btn_WWWLoad.GetComponent<Button>().onClick.AddListener(OnWWWLoadClick);
        btn_Clear.GetComponent<Button>().onClick.AddListener(OnBtnClearClick);
        btn_Save.GetComponent<Button>().onClick.AddListener(SaveHadCopyTxt);

        //清空默认节点
        Drd_JpgList.options.Clear();

        //初始化
        Dropdown.OptionData op1 = new Dropdown.OptionData();
        op1.text = "1.jpg";
        Drd_JpgList.options.Add(op1);

        Dropdown.OptionData op2 = new Dropdown.OptionData();
        op2.text = "2.jpg";
        Drd_JpgList.options.Add(op2);

        Dropdown.OptionData op3 = new Dropdown.OptionData();
        op3.text = "3.jpg";
        Drd_JpgList.options.Add(op3);

        Debug.Log(Drd_JpgList.options[Drd_JpgList.value].text);
        Drd_JpgList.captionText.text = Drd_JpgList.options[Drd_JpgList.value].text;
        
    }

    void OnIOLoadClick()
    {
        fileName = Drd_JpgList.captionText.text;
        //LoadByIO(filePath + fileName);
        LoadByIO(saveFilePath +"/"+ fileName);//同步加载
    }

    void OnWWWLoadClick()
    {
        fileName = Drd_JpgList.captionText.text;
        StartCoroutine(LoadByWWW(filePath + fileName));
    }

    void OnBtnClearClick()
    {
        image.sprite = null;
        image1.sprite = null;
    }

    private void Update()
    {
        if (Input.GetKeyDown(KeyCode.Return) || Input.GetKeyDown(KeyCode.Escape))
        {
            Application.Quit();
        }
    }

    private void LoadByIO(string path)
    {
        tips.text = path;
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        if (!File.Exists(path))
            return;
        FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read);
      
        fileStream.Seek(0, SeekOrigin.Begin);
        Debug.Log("fileSize:"+fileStream.Length);
        //创建文件缓冲区
        byte[] bytes = new byte[fileStream.Length];
        //读取文件
        fileStream.Read(bytes, 0, (int)fileStream.Length);
        fileStream.Close();
        fileStream.Dispose();
        fileStream = null;
        sw.Stop();
        Debug.Log("load by IO time:"+sw.ElapsedMilliseconds);
        tips.text = "load by IO time:" + sw.ElapsedMilliseconds;
        //创建texture
        int width = 300;
        int height = 370;
        Texture2D texture = new Texture2D(width, height);
        texture.LoadImage(bytes);

        Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height),new Vector2(0.5f,0.5f));
        image.sprite = sprite;
    }

    private IEnumerator LoadByWWW(string path)
    {
        tips.text = path;
        System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();
        sw.Start();
        string url = path;
        Debug.Log(url);
        WWW www = new WWW(url);
        yield return www;
        if (www != null && string.IsNullOrEmpty(www.error))
        {
            Texture2D texture = www.texture;
            sw.Stop();
            Debug.Log("www size:"+www.size);
            Debug.Log("load by WWW time:" + sw.ElapsedMilliseconds);
            tips.text = "load by WWW time:" + sw.ElapsedMilliseconds;
            Sprite sprite = Sprite.Create(texture, new Rect(0, 0, texture.width, texture.height), new Vector2(0.5f, 0.5f));
            image1.sprite = sprite;
            if (!hadWriteFileList.Contains(path))
            {
                Debug.Log(path);
                File.WriteAllBytes(saveFilePath+ Drd_JpgList.options[Drd_JpgList.value].text, www.bytes);//将jar包内的图片复制到持久化目录
                hadWriteFileList.Add(path);
            }
        }
        www.Dispose();
    }

    /// <summary>
    /// 保存已经复制到持久化目录的文件全路径
    /// </summary>
    void SaveHadCopyTxt()
    {
        FileHelper filehelper = new FileHelper();
        filehelper.DeleteFile(saveFilePath, HadCopyTxt);
        for (int i = 0; i < hadWriteFileList.Count; i++)
        {
            //以行的形式写入信息
            filehelper.CreateFile(saveFilePath, HadCopyTxt, hadWriteFileList[i]);
        }
    }

    IEnumerator AppQuit()
    {
        yield return new WaitForSeconds(0.5f);
    }
}
